#include "plotdata.h"
#include <ctime>

using namespace std;

static double *xdata = NULL, *ydata = NULL;
static int curve = 0;

PlotData::PlotData()
{
    this->Initialize();
}

PlotData::~PlotData()
{
    if(! m_observers->empty()){
        for(list<PlotObserver *>::iterator it = m_observers->begin(); it != m_observers->end(); ++ it){
            delete (*it);
        }
    }

    for(int i = 0; i < m_curveCount; i ++){
        delete [] m_xdata[i];
        delete [] m_ydata[i];
    }
}

void PlotData::Initialize()
{
    m_curveCount = 0;
	m_baseTime = 0;
    // new data array
    for(int i = 0; i < m_curveCount; i ++){
        m_xdata[i] = new double[MaxDataCount];
        m_ydata[i] = new double[MaxDataCount];
        m_pos[i] = 0;
    }

    m_observers = new list<PlotObserver *>();
}

int PlotData::getCurPos(int curve)
{
    return m_pos[curve];
}

double **PlotData::getXData()
{
    return m_xdata;
}

double **PlotData::getYData()
{
    return m_ydata;
}

int *PlotData::getPos()
{
    return m_pos;
}

int PlotData::getCurveCount()
{
    return m_curveCount;
}

std::string PlotData::getCurveName(int cur_id)
{
	return m_curveNames[cur_id];
}

int PlotData::getCurveId(std::string cur_name)
{
	for(int i = 0; i < MaxCurveCount; i ++){
		if(cur_name == m_curveNames[i]) return i;
	}
	return -1;
}

void PlotData::addCurve(std::string cur_name)
{
	m_curveNames[m_curveCount] = cur_name;
    m_xdata[m_curveCount] = new double[MaxDataCount];
    m_ydata[m_curveCount] = new double[MaxDataCount];
    m_pos[m_curveCount] = 0;

    m_curveCount ++;
}

// add a pair of data of all curves
void PlotData::addData(double x[], double y[])
{
	if(m_baseTime == 0) m_baseTime = time(NULL);
    // should check x[] and y[] length
    for(int i = 0; i < m_curveCount; i ++){
        m_xdata[i][m_pos[i]] = x[i] - m_baseTime;
        m_ydata[i][m_pos[i]] = y[i];
        m_pos[i] ++;
    }

    xdata = x;
    ydata = y;
    curve = m_curveCount;

    this->notifyObservers();
}

// add a pair of data of specific curve
void PlotData::addData(double x, double y, int curve)
{
	if(m_baseTime == 0) m_baseTime = time(NULL);
    if(curve < m_curveCount){
        m_xdata[curve][m_pos[curve]] = x - m_baseTime;
        m_ydata[curve][m_pos[curve]] = y;
        m_pos[curve] ++;
        this->notifyObservers();
    }
}

void PlotData::registerObserver(PlotObserver *observer)
{
    m_observers->push_back(observer);
}

void PlotData::removeObserver(PlotObserver *observer)
{
    m_observers->remove(observer);
}

void PlotData::notifyObservers()
{
    for(list<PlotObserver *>::iterator it = m_observers->begin(); it != m_observers->end(); ++ it){
        ((PlotObserver *)(*it))->update();
    }
}
